<template>
  <div>
    <el-card>
      <el-button icon="el-icon-plus" size="medium" type="primary" class="title" @click="addTrade">
        添加品牌
      </el-button>
      <el-table
        :data="tradeMarkData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        border
        class="mt-bottom"
      >
        <el-table-column type="index" label="序号" width="60" align="center"> </el-table-column>
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-image v-if="row" style="width: 100px; height: 100px" :src="row.logoUrl"></el-image>
          </template>
          <!-- <template slot-scope="scope"><img :src="scope.row.logoUrl" style="width: 100px; height: 100px"
              alt="图片异常"></template> -->
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="{ row }">
            <el-button @click="editor(row)" type="warning" size="mini" class="button"
              ><i class="el-icon-edit-outline icon"></i
            ></el-button>
            <el-button type="danger" @click="deleteTrade(row.id)" size="mini" class="button"
              ><i class="el-icon-delete icon"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="limit"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="tradeMarkPageTotal"
      >
      </el-pagination>
      <el-dialog
        :title="isAdd ? '添加品牌' : '修改品牌'"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <el-form label-width="100px" :rules="addTradeRule" :model="addTradeData" ref="addTradeDom">
          <el-form-item label="品牌名称" prop="tmName">
            <el-input class="input" v-model="addTradeData.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌图片" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="addTradeData.logoUrl" :src="addTradeData.logoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { reqAddTrademark, reqChangeTrademark, reqDeleteTrademark } from '@/api/tradeMark'
export default {
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    handleSizeChange(val) {
      this.limit = val
      this.request()
    },
    handleCurrentChange(val) {
      this.page = val
      this.request()
    },
    async request() {
      const { page, limit } = this
      await this.$store.dispatch('tradeMark/getTradeMarkList', { page, limit })
    },
    addTrade() {
      this.dialogVisible = true
      this.addTradeData.logoUrl = ''
      this.addTradeData.tmName = ''
      this.isAdd = true

      setTimeout(() => {
        var upload = document.querySelector('.avatar-uploader')
        upload.style.cssText = 'border:1px dashed #d9d9d9'
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    //上传成功触发的函数
    handleAvatarSuccess(res, file) {
      this.addTradeData.logoUrl = URL.createObjectURL(file.raw)

      var upload = document.querySelector('.avatar-uploader')

      upload.style.cssText = 'border:1px dashed white'
      this.$refs.addTradeDom.validate(valid => {})
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //点击确定触发的函数
    confirm() {
      this.$refs.addTradeDom.validate(async valid => {
        if (valid) {
          const { tmName, logoUrl } = this.addTradeData
          if (this.isAdd) {
            await reqAddTrademark(tmName, logoUrl)
            this.$message({
              message: '添加品牌成功!!',
              type: 'success'
            })
          } else {
            await reqChangeTrademark(this.changeId, tmName, logoUrl)
            this.$message({
              message: '修改品牌成功!!',
              type: 'success'
            })
          }

          this.dialogVisible = false
          this.request()
        } else {
          this.$message.error('表单验证未通过!!!')
          return false
        }
      })
    },
    editor(row) {
      this.isAdd = false
      this.dialogVisible = true
      const { id, tmName, logoUrl } = row
      this.addTradeData.tmName = tmName
      this.addTradeData.logoUrl = logoUrl
      this.changeId = id
    },
    async deleteTrade(id) {
      await reqDeleteTrademark(id)
      this.$message.success('删除品牌成功!!!')
      this.request()
    }
  },
  computed: {
    ...mapGetters(['tradeMarkData', 'tradeMarkPageTotal'])
  },
  beforeMount() {
    this.request()
  },
  data() {
    return {
      //点击修改时保存一个id
      changeId: '',
      isAdd: true,
      border: true,
      page: 1,
      limit: 3,
      dialogVisible: false,
      imageUrl: '',
      addTradeData: {
        logoUrl: '',
        tmName: ''
      },
      addTradeRule: {
        logoUrl: [
          {
            required: true,
            message: '请选择一张图片'
          }
        ],
        tmName: [
          {
            required: true,
            message: '请输入品牌名称',
            trigger: 'blur'
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table .warning-row {
  background: oldlace;
}

.title {
  margin-bottom: 20px;
}

.el-table .success-row {
  background: #f0f9eb;
}

.input {
  width: 400px;
  height: 30px;
}

// .avatar-uploader:deep(.el-upload) {
//   border: 1px dashed #d9d9d9;
//   border-radius: 6px;
//   cursor: pointer;
//   position: relative;
//   overflow: hidden;
// }

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 180px;
}

.avatar-uploader:deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

:deep(.avatar) {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader img {
  width: 180px;
  height: 180px;
  border-radius: 5px;
}
</style>
